package com.sea.wechat.controller;


import com.alibaba.fastjson.JSON;
import com.sea.wechat.util.AccessTokenUtil;
import com.sea.wechat.util.ResourceUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**   
 * @ClassName:     AccessTokenController   
 * @Description:   获取access_token请求  
 * @author:        wl
 * @date:          2017年7月31日 下午2:17:21     
 */  
@RestController
public class AccessTokenController {

	private static final Logger logger = LoggerFactory.getLogger(AccessTokenController.class);
	
	/**   
	 * @Title:         getAccessToken   
	 * @Description:   获取token,所有微信请求都会用到
	 * @return:        String   
	 * @author:        wl  
	 * @date:          2017年7月31日 下午4:32:43   
	 * @throws   
	 */  
	@RequestMapping(value="getAccessToken")
	public String getAccessToken(){
		logger.info("获取AccessToken");
		return AccessTokenUtil.getToken();
	}

	/**   
	 * @Title:         getJsapiTicket   
	 * @Description:   获取jssdk票据
	 * @param:         @return      
	 * @return:        String   
	 * @author:        wl  
	 * @date:          2017年8月13日 下午2:52:53   
	 * @throws   
	 */  
	@RequestMapping(value="getJsapiTicket")
	public HashMap<String, Object> getJsapiTicket(String url){
		logger.info("请求参数:[url:"+url+"]");
		HashMap<String, Object> parp = new HashMap<String, Object>();
		//赋值参数
		parp.put("appId", ResourceUtil.APPID);
		parp.put("timestamp", System.currentTimeMillis()/1000);
		parp.put("nonceStr",ResourceUtil.NONCESTR);
		parp.put("url",url);
		parp.put("signature",signature(parp));
		parp.put("jsApiList",ResourceUtil.JSAPILIST);
		logger.info("返回参数:[parp:"+JSON.toJSONString(parp)+"]");
		return parp;
	}

	private String signature(HashMap<String,Object> parp){
		String params="jsapi_ticket="+AccessTokenUtil.getJsapiTicket()+
				"&noncestr="+parp.get("nonceStr")+
				"&timestamp="+parp.get("timestamp")+
				"&url="+parp.get("url");
		logger.info("延签参数："+params);
		return DigestUtils.sha1Hex(params);
	}
}
